package org.mozhu.mboot.admin.personal.profile.web.controller;

import org.mozhu.mboot.admin.AppUtils;
import org.mozhu.mboot.admin.maintain.file.service.FileService;
import org.mozhu.mboot.admin.system.account.entity.Gender;
import org.mozhu.mboot.admin.system.account.entity.User;
import org.mozhu.mboot.admin.system.account.service.UserService;
import org.mozhu.mboot.core.web.Constants;
import org.mozhu.mboot.core.web.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

@RequestMapping("/personal/profile")
@Controller
public class ProfileController extends BaseController {

    private static final String AVATAR_BASE_PATH = "avatar";

    private static final String ORIGIN_PASSWORD_NOT_CORRECT = "profile.origin.password.not.correct";

    @Autowired
    UserService userService;

    @Autowired
    FileService fileService;

    @RequestMapping(value = {"/overview"})
    public String overview(HttpServletRequest request, Model model) {
        model.addAttribute(Constants.OP_NAME, "overview");
        return viewName("overview");
    }

    @RequestMapping(value = {"/{viewName}"})
    public String showPage(HttpServletRequest request, Model model, @PathVariable("viewName") String viewName) {
        model.addAttribute(Constants.OP_NAME, "settings");
        Long userId = AppUtils.getCurrentUserId();
        model.addAttribute("m", userService.findById(userId));
        model.addAttribute("genders", Gender.values());
        model.addAttribute("viewName", viewName);
        return viewName(viewName);
    }

    @RequestMapping(value = "/info", method = RequestMethod.POST)
    public String changeInfo(HttpServletRequest request, Model model, @Valid @ModelAttribute("m") User m, BindingResult result, RedirectAttributes redirectAttributes) {
        if (hasError(m, result)) {
            return showPage(request, model, "info");
        }
        userService.save(m);
        // TODO update info to cache
        redirectAttributes.addFlashAttribute(Constants.MESSAGE, UPDATE_SUCCESS);
        return redirect("info");
    }

    protected boolean hasError(User m, BindingResult result) {
        Assert.notNull(m, "m should not be null");
        return result.hasErrors();
    }

    @ModelAttribute
    public void getModel(Model model) {
        Long userId = AppUtils.getCurrentUserId();
        model.addAttribute("m", userService.findById(userId));
    }

    @RequestMapping(value = "/password", method = RequestMethod.POST)
    public String changePassword(HttpServletRequest request, Model model, @RequestParam(value = "oldPlainPassword", required = true) String oldPlainPassword,
                                 @RequestParam(value = "plainPassword", required = true) String plainPassword, RedirectAttributes redirectAttributes) {
        Long userId = AppUtils.getCurrentUserId();
        User user = userService.findById(userId);
        boolean valid = userService.isValidPassword(user, oldPlainPassword);
        if (!valid) {
            model.addAttribute(Constants.ERROR, ORIGIN_PASSWORD_NOT_CORRECT);
            return showPage(request, model, "password");
        }
        user.setPlainPassword(plainPassword);
        userService.encryptPassword(user);
        userService.save(user);
        redirectAttributes.addFlashAttribute(Constants.MESSAGE, UPDATE_SUCCESS);
        return redirect("password");
    }

    @RequestMapping(value = "/avatar", method = RequestMethod.POST)
    public String uploadAvatar(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {
        if (!file.isEmpty()) {
            String newAvatarPath = fileService.copyFileToDir(file, AVATAR_BASE_PATH);
            User user = userService.findById(AppUtils.getCurrentUserId());
            String oldAvatar = user.getAvatar();
            user.setAvatar(newAvatarPath);
            userService.save(user);
            fileService.deleteFile(oldAvatar);
            // TODO update user cache ?
        }
        redirectAttributes.addFlashAttribute(Constants.MESSAGE, UPDATE_SUCCESS);
        return redirect(AVATAR_BASE_PATH);
    }


}